package com.lenovo.smarttraffic.ui.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.LifeHelper.AllWeatherInfo;
import com.lenovo.smarttraffic.bean.LifeHelper.TemperatureInfo;
import com.lenovo.smarttraffic.database.dao.LifeHelperDatabase;
import com.lenovo.smarttraffic.ui.adapter.LifeHelperViewPagerAdapter;
import com.lenovo.smarttraffic.ui.fragment.LifeHelper.AirFragment;
import com.lenovo.smarttraffic.ui.fragment.LifeHelper.Co2Fragment;
import com.lenovo.smarttraffic.ui.fragment.LifeHelper.HumidityFragment;
import com.lenovo.smarttraffic.ui.fragment.LifeHelper.TemperatureFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LifeHelperActivity extends BaseActivity implements View.OnClickListener {

    private List<TemperatureInfo.ROWS_DETAIL> temList;
    private TemperatureInfo temInfo;
    private TextView tvNowTem;
    private TextView tvIntervalTem;
    private ImageView imageRefresh;
    private WebView intervalTemWebView;
    private AllWeatherInfo allInfo;
    private TextView tvIllGrade;
    private TextView tvIllRemarks;
    private TextView tvColdGrade;
    private TextView tvColdRemarks;
    private TextView tvClothesGrade;
    private TextView tvClothesRemarks;
    private TextView tvExerciseGrade;
    private TextView tvExerciseRemarks;
    private TextView tvPollutionGrade;
    private TextView tvPollutionRemarks;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private TextView tv4;
    private ViewPager viewPager;
    private LifeHelperDatabase lifeHelperDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //自定义标题栏
        initToolBar(findViewById(R.id.toolbar),true, getString(R.string.item13));
        //初始化所有控件
        init();
        //配置ViewPager滑动界面
        setViewPager();
        //初始化当前温度与今天温度区间
        sendTemData();
        //每3秒请求一次所有传感器的值
        handler.sendEmptyMessage(0x001);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x001) {
                sendAllWeatherData();
            }
            handler.sendEmptyMessageDelayed(0x001, 3000);
        }
    };

    //请求所有传感器的值
    public void sendAllWeatherData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   OkHttpClient client = new OkHttpClient();
                   RequestBody requestBody = RequestBody.create(MediaType.parse("app/jaon"),
                           "{\"UserName\":\"user1\"}");
                   Request request = new Request.Builder()
                           .url("http://192.168.1.102:8088/transportservice/action/GetAllSense.do")
                           .post(requestBody)
                           .build();
                   Response response = client.newCall(request).execute();
                   String responseData = response.body().string();
                   //数据解析
                    parseAllWeatherData(responseData);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void parseAllWeatherData(String jsonData) {
        Gson gson = new Gson();
        allInfo = gson.fromJson(jsonData, AllWeatherInfo.class);
        //判断各传感器的值，显示不同数据
        showLifeLiving();
        //将请求的值添加到数据库中
        SimpleDateFormat df = new SimpleDateFormat("ss");   //获取时间
        String time = df.format(new Date());
        SQLiteDatabase db = lifeHelperDatabase.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("pm25", allInfo.getPm25());
        values.put("temperature", allInfo.getTemperature());
        values.put("humidity", allInfo.getHumidity());
        values.put("co2", allInfo.getCo2());
        values.put("time", time);
        db.insert("AllWeather", null, values);
        //判断数据库的长度是否超过了20位，若超过就删除前面的数据
        exceedLong();
    }
    //判断数据库的长度是否超过了20位，若超过就删除前面的数据
    public void exceedLong() {
        SQLiteDatabase db = lifeHelperDatabase.getWritableDatabase();
        while (true) {
            Cursor cursor = db.rawQuery("select * from AllWeather", null);
            if (cursor.getCount() > 20) {
                //查找出第一行数据的id
                int firstNum = 1;
                Cursor cursor1 = db.query("AllWeather", null, null, null, null, null, null);
                if (cursor1.moveToFirst()) {
                    firstNum = cursor1.getInt(cursor1.getColumnIndex("id"));
                }
                cursor1.close();
                db.delete("AllWeather", "id = "+firstNum+"", null);
                Log.d("text", cursor.getCount()+"");
            } else {
                break;
            }
        }
    }

    //配置ViewPager滑动界面
    public void setViewPager() {
        //绑定ViewPager滑动事件
        viewPager.setOnPageChangeListener(new MyPagerChangeLisition());
        //将所有的滑动碎片都添加到List<Fragment>集合中
        List<Fragment> list = new ArrayList<>();
        list.add(new AirFragment());
        list.add(new TemperatureFragment());
        list.add(new HumidityFragment());
        list.add(new Co2Fragment());
        LifeHelperViewPagerAdapter adapter = new LifeHelperViewPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);    //初始显示第一个页面
    }
    //ViewPager滑动监听事件
    public class MyPagerChangeLisition implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    tv1.setBackgroundResource(R.drawable.life_helper_tv_hane);
                    tv2.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv3.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv4.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    break;
                case 1:
                    tv1.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv2.setBackgroundResource(R.drawable.life_helper_tv_hane);
                    tv3.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv4.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    break;
                case 2:
                    tv1.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv2.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv3.setBackgroundResource(R.drawable.life_helper_tv_hane);
                    tv4.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    break;
                case 3:
                    tv1.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv2.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv3.setBackgroundResource(R.drawable.life_helper_tv_nohave);
                    tv4.setBackgroundResource(R.drawable.life_helper_tv_hane);
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    //判断各传感器的参数，显示不同的值
    public void showLifeLiving() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //紫外线强度
                if (allInfo.getLightIntensity() > 0 && allInfo.getLightIntensity() < 1000) {
                    tvIllGrade.setText("弱（"+allInfo.getLightIntensity()+"）");
                    tvIllRemarks.setText("辐射较弱，涂擦SPF12~15、PA+护肤品");
                } else if (allInfo.getLightIntensity() >= 1000 && allInfo.getLightIntensity() <= 3000) {
                    tvIllGrade.setText("中等（"+allInfo.getLightIntensity()+"）");
                    tvIllRemarks.setText("涂擦SPF大于15、PA+防晒护肤品");
                } else {
                    tvIllGrade.setText("强（"+allInfo.getLightIntensity()+"）");
                    tvIllRemarks.setText("尽量减少外出，需要涂抹高倍数防晒霜");
                }
                //感冒指数
                if (allInfo.getTemperature() < 8) {
                    tvColdGrade.setText("较易发（"+allInfo.getTemperature()+"）");
                    tvColdRemarks.setText("温度低，风较大，较易发生感冒，注意防护");
                } else {
                    tvColdGrade.setText("少发（"+allInfo.getTemperature()+"）");
                    tvColdRemarks.setText("无明显降温，感冒机率较低");
                }
                //穿衣指数
                if (allInfo.getTemperature() < 12) {
                    tvClothesGrade.setText("冷（"+allInfo.getTemperature()+"）");
                    tvClothesRemarks.setText("建议穿长袖衬衫、单裤等服装");
                } else if (allInfo.getTemperature() >= 12 && allInfo.getTemperature() <= 21) {
                    tvClothesGrade.setText("舒适（"+allInfo.getTemperature()+"）");
                    tvClothesRemarks.setText("建议穿短袖衬衫、单裤等服装");
                } else {
                    tvClothesGrade.setText("热（"+allInfo.getTemperature()+"）");
                    tvClothesRemarks.setText("适合穿T恤、短薄外套等夏季服装");
                }
                //运动指数
                if (allInfo.getCo2() > 0 && allInfo.getCo2() < 3000) {
                    tvExerciseGrade.setText("适宜（"+allInfo.getCo2()+"）");
                    tvExerciseRemarks.setText("气候适宜，推荐您进行户外运动");
                } else if (allInfo.getCo2() >= 3000 && allInfo.getCo2() <= 6000) {
                    tvExerciseGrade.setText("较适宜（"+allInfo.getCo2()+"）");
                    tvExerciseRemarks.setText("易感人群应适当减少室外活动");
                } else {
                    tvExerciseGrade.setText("较不宜（"+allInfo.getCo2()+"）");
                    tvExerciseRemarks.setText("空气氧气含量低，请在室内进行休闲运动");
                }
                //空气污染扩散指数
                if (allInfo.getPm25() > 0 && allInfo.getPm25() < 30) {
                    tvPollutionGrade.setText("优（"+allInfo.getPm25()+"）");
                    tvPollutionRemarks.setText("空气质量非常好，非常适合户外活动，趁机出去多呼吸新鲜空气");
                } else if (allInfo.getPm25() >= 30 && allInfo.getPm25() <= 100) {
                    tvPollutionGrade.setText("良（"+allInfo.getPm25()+"）");
                    tvPollutionRemarks.setText("易感人群应适当减少室外活动");
                } else {
                    tvPollutionGrade.setText("污染（"+allInfo.getPm25()+"）");
                    tvPollutionRemarks.setText("空气质量差，不适合户外活动");
                }
            }
        });
    }

    //初始化控件
    public void init() {
        tvNowTem = findViewById(R.id.life_helper_nowtemperature);
        tvIntervalTem = findViewById(R.id.life_helper_intervaltemperature);
        imageRefresh = findViewById(R.id.life_helper_refresh);
        imageRefresh.setOnClickListener(this);
        intervalTemWebView = findViewById(R.id.life_helper_webview1);
        tvIllGrade = findViewById(R.id.life_helper_ill_grade);
        tvIllRemarks = findViewById(R.id.life_helper_ill_remrks);
        tvColdGrade = findViewById(R.id.life_helper_cold_grade);
        tvColdRemarks = findViewById(R.id.life_helper_cold_remrks);
        tvClothesGrade = findViewById(R.id.life_helper_clothes_grade);
        tvClothesRemarks = findViewById(R.id.life_helper_clothes_remrks);
        tvExerciseGrade = findViewById(R.id.life_helper_exercise_grade);
        tvExerciseRemarks = findViewById(R.id.life_helper_exercise_remrks);
        tvPollutionGrade = findViewById(R.id.life_helper_pollution_grade);
        tvPollutionRemarks = findViewById(R.id.life_helper_pollution_remrks);
        viewPager = findViewById(R.id.life_helper_viewpager);
        tv1 = findViewById(R.id.life_helper_viewpager_tv1);
        tv2 = findViewById(R.id.life_helper_viewpager_tv2);
        tv3 = findViewById(R.id.life_helper_viewpager_tv3);
        tv4 = findViewById(R.id.life_helper_viewpager_tv4);
        //初始化WebView界面
        intervalTemWebView.loadUrl("file:///android_asset/LifeHelper/IntervalTemperature.html");
        intervalTemWebView.setWebViewClient(new WebViewClient());
        intervalTemWebView.getSettings().setJavaScriptEnabled(true);
        //创建数据库
        lifeHelperDatabase = new LifeHelperDatabase(this, "LifeHelper.db", null, 1);
        lifeHelperDatabase.getWritableDatabase();
    }

    //请求温度区间的数据
    public void sendTemData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                            "{\"UserName\":\"user1\"}");
                    Request request = new Request.Builder()
                            .url("http://192.168.1.102:8088/transportservice/action/GetWeather.do")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    //解析数据
                    parseTemData(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void parseTemData(String jsonData) {
        Gson gson = new Gson();
        temInfo = gson.fromJson(jsonData, TemperatureInfo.class);
        temList = new ArrayList<>();
        temList.addAll(temInfo.getROWS_DETAIL());
        //获取当前温度和今天的区间温度
        showTem();
        //获取每天的区间温度，传递给Web
        showIntervalTem();
    }

    /**
     * 获取每天的区间温度，传递给Web
     */
    public void showIntervalTem(){
        String[] maxTem = new String[temList.size()];
        String[] minTem = new String[temList.size()];
        for (int i = 0; i < temList.size(); i++) {
            String[] tems = temList.get(i).getTemperature().split("~");
            minTem[i] = tems[0];
            maxTem[i] = tems[1];
        }
        //将两个数组传递给WebView
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                intervalTemWebView.loadUrl("javascript:getData(\""+ Arrays.toString(maxTem) +"\", \""+Arrays.toString(minTem)+"\")");
            }
        });
    }

    /**
     * 获取当前温度和今天的区间温度
     */
    public void showTem() {
        //获取当前温度
        int nowTem = temInfo.getWCurrent();
        //获取温度区间
        String intervalTem = temList.get(1).getTemperature();
        //显示到UI界面上
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvNowTem.setText(nowTem+"°");
                tvIntervalTem.setText("今天："+intervalTem+"℃");
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.life_helper_refresh:
                sendTemData();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭活动时停止Handler消息传递
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_life_helper;
    }
}
